import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/login_info_entity.dart';
import 'package:seedfour/app/remote/request.dart';
import 'package:seedfour/app/routes/app_routes.dart';
import 'package:seedfour/app/services/api_service.dart';
import 'package:seedfour/app/views/web_screen/screen_params.dart';

import '../../../toolkit/utils/encrypt_utils.dart';
import '../../checkupdate/update_dialog.dart';
import '../../checkupdate/update_service.dart';

class LoginLogic extends GetxController {
  var usernameController = TextEditingController().obs;
  var passwordController = TextEditingController().obs;
  var isLoading = false.obs;
  var isAgree = false.obs;

  final ApiService apiService = Get.find();
  // final Fluwx fluwx = Fluwx();

  final agreementUrl = 'https://api.seedfour.com/res/api/v1/user/agreement';
  final privacyUrl = 'https://api.seedfour.com/res/api/v1/user/privacy';

  @override
  void onInit() {
    // fluwx.addSubscriber((response) => _wxLogin(response));
    super.onInit();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await UpdateService.doCheckForUpdates();
    });
  }

  void login() async {
    String mobile = usernameController.value.value.text;
    String password = passwordController.value.value.text;

    if (isAgree.value == false) {
      Get.snackbar('提示', '请先阅读并同意用户协议');
      return;
    }

    if (mobile.isEmpty || password.isEmpty) {
      Get.snackbar('提示', '请输入手机号和密码');
      return;
    }

    var payKey = await apiService.getPayKey();
    if (payKey.isBlank ?? true) {
      EasyLoading.dismiss();
      EasyLoading.showError('登录失败，请稍后重试！');
      return;
    }

    password = rsaEncrypt(payKey!, password);

    _login(mobile, password);
  }

  void onClickAgreement() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: agreementUrl));
  }

  void onClickPrivacy() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: privacyUrl));
  }

  void _login(String mobile, String password) => request(
        () async {
          isLoading.value = true;
          LoginInfoEntity? result = await apiService.login(
            mobile,
            password,
            onError: (error) => isLoading.value = false,
          );

          isLoading.value = false;

          if (result != null) {
            _loginSuccess();
          }
        },
        showLoading: true,
      );

  void _loginSuccess() {
    apiService.getUserInfo().then((value) {
      isLoading.value = false;
      if (value != null) {
        Get.snackbar('提示', '登录成功');
        Get.offAllNamed(RouteGet.main);
      }
    });
  }

  void wxAuth() {
    // fluwx.authBy(
    //     which: NormalAuth(
    //         scope: 'snsapi_userinfo', state: 'wechat_sdk_demo_test'));
  }

  // void _wxLogin(WeChatResponse response) {
  //   if (response is WeChatAuthResponse) {
  //     isLoading.value = true;
  //     apiService.wxLogin(response.code).then((value) {
  //       if (value != null) {
  //         Get.snackbar('提示', '登录成功');
  //         Get.offAllNamed(RouteGet.main);
  //       } else {
  //         isLoading.value = false;
  //       }
  //     });
  //   }
  // }
}
